package com.example.smartcity_ikun3.ui.home

import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.smartcity_ikun3.R
import com.example.smartcity_ikun3.logic.base.BaseFragment
import com.example.smartcity_ikun3.logic.model.WeatherModel
import com.example.smartcity_ikun3.logic.network.RetrofitService.Companion.create
import com.example.smartcity_ikun3.logic.network.SmartApi
import com.example.smartcity_ikun3.logic.util.Util.guide
import com.example.smartcity_ikun3.logic.util.Util.show
import com.example.smartcity_ikun3.ui.App.Companion.url
import com.example.smartcity_ikun3.ui.home.activity.NewsActivity
import com.example.smartcity_ikun3.ui.home.activity.NewsShowActivity
import com.example.smartcity_ikun3.ui.home.activity.WeatherActivity
import com.example.smartcity_ikun3.ui.home.adapter.ReAdapterMore
import com.example.smartcity_ikun3.ui.home.adapter.ReAdapterNews
import com.example.smartcity_ikun3.ui.home.adapter.ReAdapterWeather
import com.example.smartcity_ikun3.ui.home.model.MoreEntity
import com.example.smartcity_ikun3.ui.home.model.NewsEntity
import com.example.smartcity_ikun3.ui.home.model.WeatherEntity
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlinx.android.synthetic.main.fragment_home.*

class HomeFragment : BaseFragment() {

    private val viewModel by lazy {
        ViewModelProviders.of(this).get(HomeViewModel::class.java)
    }

    private lateinit var mBanner: Banner<*,*>
    private lateinit var mMoreRecyclerView: RecyclerView
    private lateinit var mWeatherRecyclerView: RecyclerView
    private lateinit var mNewsRecyclerView: RecyclerView
    private lateinit var mNewsIsData: TextView
    private lateinit var mWeatherAdd: TextView
    private lateinit var mWeatherLayout: LinearLayout
    private lateinit var mNewsLayout: LinearLayout

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_home, container, false)
        mBanner = root.findViewById(R.id.homeBanner)
        mMoreRecyclerView = root.findViewById(R.id.homeMore)
        mWeatherRecyclerView = root.findViewById(R.id.homeWeatherRecyclerView)
        mNewsRecyclerView = root.findViewById(R.id.homeNewsRecyclerView)
        mNewsIsData = root.findViewById(R.id.homeNewsIsData)
        mWeatherAdd = root.findViewById(R.id.WeatherAdd)

        mWeatherLayout = root.findViewById(R.id.WeatherLayout)
        mNewsLayout = root.findViewById(R.id.NewsLayout)


        setData()

        // Banner
        setBanner()

        // setMore
        setMore()

        // weather
        setWeather()

        // setNews
        setNews()


        return root
    }

    override fun getLayout(): Int {
        return R.layout.fragment_home
    }

    override fun initData() {

    }

    override fun initView() {

    }

    override fun initEvent() {

    }


    /**
     * 处理点击事件
     */
    private fun setData(){
        // 点击进入更多咨询页面
        mNewsIsData.setOnClickListener {
            startActivity(Intent(context, NewsActivity::class.java))
        }

        // 点击进入近7天天气
        mWeatherAdd.setOnClickListener {
            startActivity(Intent(context, WeatherActivity::class.java))
        }
    }


    // banner
    private fun setBanner(){
        val array = ArrayList<String>()
        viewModel.setBanner("")
        viewModel.bannerLiveData.observe(this, Observer {
            if (it.code == "200"){
                viewModel.bannerList.clear()
                viewModel.bannerList.addAll(it.rows!!)
            }

            for (i in viewModel.bannerList){
                if (array.size < viewModel.bannerList.size) array.add(url + i.advImg)
            }

            mBanner.apply {
                this.adapter = object : BannerImageAdapter<String>(array){
                    override fun onBindView(p0: BannerImageHolder?, p1: String?, p2: Int, p3: Int) {
                        guide(p1.toString(), p0?.imageView!!)
                    }

                }
                this.addBannerLifecycleObserver(this@HomeFragment).indicator = CircleIndicator(context)
                this.setBannerRound(25F)
                this.setOnBannerListener { any, i ->
                    if (i == 0){
                        startActivity(Intent(context, NewsShowActivity::class.java).apply {
                            putExtra("title", "报告显示：农村地区学生手机依赖比例高于城市学生")
                        })
                    }

                    if (i == 1){
                        startActivity(Intent(context, NewsShowActivity::class.java).apply {
                            putExtra("title", "书法考研怎么准备？有什么好的建议")
                        })
                    }

                    if (i == 2){
                        startActivity(Intent(context, NewsShowActivity::class.java).apply {
                            putExtra("title", "2021中国星秀英文大赛 共同为爱发声")
                        })
                    }

                }
            }
        })

    }


    /**
     * setMore
     */
    private fun setMore(){
        val array = ArrayList<MoreEntity>()

        viewModel.setGetMore(1)
        viewModel.getMoreLiveData.observe(this, Observer {
            if (it.code == 200){
                viewModel.getMoreList.clear()
                viewModel.getMoreList.addAll(it.data!!)
                MoreLayout.visibility = View.VISIBLE
            }

            for (i in viewModel.getMoreList){
                if (array.size < viewModel.getMoreList.size){
                    array.add(MoreEntity(url + i.imgUrl.toString(), i.liveName.toString()))
                    mMoreRecyclerView.adapter?.notifyItemChanged(array.size)
                }
            }
        })

        mMoreRecyclerView.apply {
            this.layoutManager = GridLayoutManager(context, 4)
            this.adapter = ReAdapterMore(array)
        }
    }


    /**
     * 获取天气
     */
    private fun setWeather(){
        val array = ArrayList<WeatherEntity>()

        create<SmartApi>().getWeather().enqueue(object : Callback<WeatherModel>{
            override fun onFailure(p0: Call<WeatherModel>, p1: Throwable) {
                "加载天气失败！".show()
                Log.d("NET", "onResponse: Weather ---> ${p1.message}")
            }

            override fun onResponse(p0: Call<WeatherModel>, p1: Response<WeatherModel>) {
                val body = p1.body()
                if (body != null) if (body.code == 200){
                    val wendu = "${body.data.maxTemperature}' / ${body.data.minTemperature}'"
                    array.add(WeatherEntity(
                        R.mipmap.weather1,
                        body.data.weather,
                        wendu,
                        "空气质量: ${body.data.air}",
                        "湿度: ${body.data.humidity}"
                    ))

                    // array.add(WeatherEntity(R.mipmap.weather1, "1","2", "3","4"))
                    mWeatherRecyclerView.apply {
                        this.layoutManager = LinearLayoutManager(context)
                        this.adapter = ReAdapterWeather(array)
                    }

                    mWeatherLayout.visibility = View.VISIBLE

                }else "获取天气失败！".show()
            }
        })



    }



    /**
     * 新闻
     */
    private fun setNews(){
        val array = ArrayList<NewsEntity>()

        mNewsRecyclerView.apply {
            this.layoutManager = LinearLayoutManager(context)
            this.adapter = ReAdapterNews(array)
        }

        viewModel.setNewsHot("N")
        viewModel.newsLiveDataHot.observe(this, Observer {
            if (it.code == 200){
                viewModel.newsListHot.clear()
                viewModel.newsListHot.addAll(it.rows!!)
                mNewsLayout.visibility = View.VISIBLE
            }

            for (i in viewModel.newsListHot){
                if (array.size < 3){
                    array.add(
                        NewsEntity(
                        i.title.toString(),
                        url + i.cover,
                        i.content.toString(),
                        i.publishDate.toString())
                    )
                    mNewsRecyclerView.adapter?.notifyItemChanged(array.size)
                }
            }
        })
    }

}